package com.jason.bookworm.service.impl;

import com.jason.bookworm.dao.pojo.LoginUser;
import com.jason.bookworm.dao.pojo.User;
import com.jason.bookworm.exception.ServiceException;
import com.jason.bookworm.response.StatusEnum;
import com.jason.bookworm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    /**
     * @param username 根据用户名从数据库中查找该对象
     * @return 用户信息对象
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从UserService获取User对象
        User user = userService.getOneUser(username);
        if(Objects.isNull(user)){
            throw new ServiceException(StatusEnum.Login_ERR, "用户名或密码不正确！请重新输入。");
        }
        //将数据封装成UserDetails
        return new LoginUser(user);
    }
}
